package com.quectel.util.udp;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * udp接收
 *
 * @author: caolu
 * @email: louis.cao@quectel.com
 * @date: 2022-08-08 11:50:00
 */
@Slf4j
public class UdpReceiver {
    public static void main(String[] args) throws SocketException {
        //1
        DatagramSocket serverSocket = new DatagramSocket(4000);
        //2
        byte[] arr = new byte[1024];
        DatagramPacket packet = new DatagramPacket(arr, arr.length);

        while (true) {
            //3 当程序运行起来之后,receive方法会一直处于监听状态
            try {
                serverSocket.receive(packet);
                //从包中将数据取出
                byte[] dataArr = packet.getData();
                System.out.println(new String(dataArr, 0, packet.getLength()));

            } catch (IOException e) {
                log.warn("receive data error", e);
            }

        }
//        serverSocket.close();
    }
}
